package org.hk.proxy.server.handlers;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.hk.proxy.common.constant.CommonKey;
import org.hk.proxy.protocol.ProxyMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NextChannelExchangeHandler extends ChannelInboundHandlerAdapter {
    private static final Logger log = LoggerFactory.getLogger(NextChannelExchangeHandler.class);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
         Channel nextChannel =  ctx.channel().attr(CommonKey.NEXT_CHANNEL).get();
         if(nextChannel!=null){
             ProxyMessage proxyMessage = new ProxyMessage();
             proxyMessage.setType(ProxyMessage.P_TYPE_TRANSFER);
             ByteBuf buf = (ByteBuf) msg;
             byte[] data = new byte[buf.readableBytes()];
             buf.readBytes(data);
             proxyMessage.setData(data);
             nextChannel.writeAndFlush(proxyMessage);
         }
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("lost connection remote address:{},local address:{}",ctx.channel().remoteAddress(),ctx.channel().localAddress());
        Channel nextChannel =  ctx.channel().attr(CommonKey.NEXT_CHANNEL).getAndSet(null);
        nextChannel.close();
    }
}
